define(["jquery", "cookie"], cookie => {
  class Header {
    constructor() {
      //header的内容是通过load方法异步加载的，所以要load成功回调里才能反问道header里面的DOM元素
      //把异步代码封装成promise
      //这样的好处是：把核心逻辑放在constructor里面而不是loadHTML里，loadHTML的逻辑更加单纯，易于维护
      this.loadHMTL().then(() => {
        this.search();
        this.calcCartCount();
        this.calcCookie();
      });
    }
    loadHMTL() {
      return new Promise(resolve => {
        $("header").load("/html/modules/header.html", () => {
          resolve();
        });
      });
    }
    search() {
      $("#input_search").on("keyup", function() {
        console.log($(this).val());
      });
    }
    calcCartCount() {
      let cart = localStorage.getItem("cart");
      let count = 0;
      if (cart) {
        cart = JSON.parse(cart);
        count = cart.reduce((sum, shop) => {
          sum += shop.count;
          return sum;
        }, 0);
      }
      $("#shopnum,#cart span").html(count);
    }
    calcCookie() {
      // let username = $("#username");
      // let LoginNone = $(".LoginNone");
      // let LoginModule = $(".LoginModule");

      let LoginUser = $.cookie("loginUser");
      console.log($.cookie("loginUser"));
      if (LoginUser) {
        // console.log(LoginUser);
        LoginUser = JSON.parse(LoginUser);
        // console.log(JSON.parse(LoginUser));
        $(".LoginModule").hide();
        $(".LoginNone").show();
        $("#username").html(LoginUser.username);
        // console.log($("#username"));
        // console.log(LoginUser.username);
      }
    }
  }
  return new Header();
});
